package com.timothy.android;


import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import com.timothy.android.handler.MyCrashHandler;
import com.timothy.android.util.SysUtil;
import com.timothy.service.MessageReceiveService;
import com.timothy.service.MessageSender;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.content.SharedPreferences; 


public class LoginActivity extends BaseActivity {
	/** Called when the activity is first created. */
	private static final String LOG_TAG = "LoginActivity";
	
	private EditText hostAddr = null;
	private EditText hostPort = null;
	private Button loginBtn = null;
	private LinearLayout layout1;
	
	   //这里用来接受退出程序的指令 
    @Override
    protected void onStart() {
    	Log.i(LOG_TAG, "onStart()...");
    	int flag = getIntent().getIntExtra("flag", 0);
    	Log.i(LOG_TAG, "flag="+flag);
    	if(flag == SysUtil.EXIT_APPLICATION){
    		finish();
    	}
    	super.onResume();
    	
    }
    
    @Override
    protected void onResume() {
    	super.onStart();
    	Log.i(LOG_TAG, "onResume()...");
    }
    
    //当activity是单例的时候,再次启动该activity就不会再调用 oncreate->onstart这些方法了
    @Override
    protected void onNewIntent(Intent intent) {
    	Log.i(LOG_TAG, "onNewIntent()...");
    	int flag = getIntent().getIntExtra("flag", 0);
    	Log.i(LOG_TAG, "flag="+flag);
    	if(flag == SysUtil.EXIT_APPLICATION){
    		finish();
    	}
    	super.onNewIntent(intent);
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		Log.i(LOG_TAG, "onResume()...");
		
		this.setTitle("(Address:"+ getWifiIP()+")");
		
		layout1 = (LinearLayout) this.findViewById(R.id.layout1);
		layout1.setBackgroundDrawable(bgPic);
		
		hostAddr = (EditText) this.findViewById(R.id.hostAddr);
		hostPort = (EditText) this.findViewById(R.id.hostPort);
		
		//get information from history, if exist, set history information to components
		String preHostAddr = sharedPreferences.getString("pcip", null);  
		int preHostPort = sharedPreferences.getInt("pcport", 0);
		
		Log.i(LOG_TAG, "load history from sharedPreferences:host="+preHostAddr);
		Log.i(LOG_TAG, "load history from sharedPreferences:port="+preHostPort);
		
		if(preHostAddr!=null) hostAddr.setText(preHostAddr);
		if(preHostPort!=0) hostPort.setText(String.valueOf(preHostPort));
		
		loginBtn = (Button) this.findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				
				MessageSender.PC_IP =  hostAddr.getText().toString();
				MessageSender.PC_PORT = Integer.valueOf( hostPort.getText().toString() );
				
				//get wifi service 
		        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		        
		        //check wifi is enabled 
		        if (!wifiManager.isWifiEnabled()) { 
		        	ShowDialog("Wifi is not available!");
		        	return;
		        } 
		        
		        //test wifi network
		        MessageSender.PHONE_IP = getWifiIP();
		        if ( MessageSender.PHONE_IP==null || MessageSender.PHONE_IP.equals("") || MessageSender.PHONE_IP.equals("0.0.0.0")) { 
		        	//wifiManager.setWifiEnabled(true);  
		        	ShowDialog("Your mobile is not in a available NetWork!");
		        	return;
		        } 
		        
		        //Send Phone Information to PC
				if(!MessageSender.sendMessage( MessageSender.Get_Base_Stations) ) {
					ShowDialog("Can not login Server!");
				}else{
					//save information to local
					SharedPreferences.Editor editor = sharedPreferences.edit();
					editor.putString("pcip", hostAddr.getText().toString());  
					editor.putInt("pcport", Integer.valueOf(hostPort.getText().toString())); 
					editor.commit();
				}
				
			}			
		});
	}
	
	@Override
	protected void processMessage(int what, String content) {
		// TODO Auto-generated method stub
		Log.i(LOG_TAG,"what="+what+" content=" + content);
		if( MessageReceiveService.MSG_BASE_STATION == what ) {
			Intent intent = new Intent();
			intent.putExtra("baseStationStr", content);//save baseStationStr
			intent.putExtra("hostIp", hostAddr.getText().toString());//save hostIp
			intent.putExtra("hostPort", Integer.valueOf( hostPort.getText().toString()));//save hostPort
			intent.setClass( getBaseContext(), BaseStations.class);
			startActivity(intent);
		}		
	}
	
	/**
	 * 
	 * @param ipAddress
	 * @return
	 */
	public boolean pingIP(String ipAddress) {
		Log.i(LOG_TAG, "Ping Poller Starts...");
		// String ipAddress = "localhost";
		boolean pingResult = true;
		try {
			InetAddress inet = InetAddress.getByName(ipAddress);
			System.out.println("Sending Ping Request to " + ipAddress);
			Log.i(LOG_TAG, "IP:"+ipAddress);
			boolean status = inet.isReachable(5000); // Timeout = 5000 milli
			if (status) {
				Log.i(LOG_TAG, "Status : Host is reachable");
			} else {
				Log.i(LOG_TAG, "Status : Host is not reachable");
				pingResult = false;
			}
		} catch (UnknownHostException e) {
			System.err.println("Host does not exists");
			Log.i(LOG_TAG, "Host does not exists");
			pingResult = false;
		} catch (IOException e) {
			System.err.println("Error in reaching the Host");
			Log.i(LOG_TAG, "Error in reaching the Host");
			pingResult = false;
		}
		return pingResult;
	}
	
	private String getWifiIP() {
		// get wifi service
		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		// is wifi enabled
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = intToIp(ipAddress);
		Log.i("BaseStations","WIFI IP:" + ip);
		return ip;
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}
	
}
